package com.star.common.notify;

import com.star.common.notify.config.DingTaskProperties;
import com.star.common.notify.service.StarDingTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * bean的后置处理器加锁对象，采用aop方式
 *
 * @author xjt
 * @date 2023/6/7 15:57
 */
@Slf4j
@Component
public class StarDingTaskBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {
    private BeanFactory beanFactory;

    @Autowired
    private Map<String, DingTaskProperties> dingtaskPropertiesMap;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (Initialized.allowInit(dingtaskPropertiesMap)) {
            for (Map.Entry<String, DingTaskProperties> entry : dingtaskPropertiesMap.entrySet()) {
                String dingTaskName = "dingtask" + ":" + entry.getKey();
                BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
                registerCzDingTaskClient(registry, dingTaskName, entry.getValue());
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }

    private void registerCzDingTaskClient(BeanDefinitionRegistry registry,
                                          String dingTaskName,
                                          DingTaskProperties dingTaskProperties) {
        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(StarDingTaskService.class);
        GenericBeanDefinition genericBeanDefinition = (GenericBeanDefinition) definitionBuilder.getBeanDefinition();
        genericBeanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, dingTaskProperties);
        registry.registerBeanDefinition(dingTaskName, genericBeanDefinition);
        log.info("star-common-notify register`dingTaskName=" + dingTaskName);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }
}
